package pe.gob.essalud.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import pe.gob.essalud.service.UsuarioService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UsuarioService loginService;
	
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    	auth
    		.userDetailsService(loginService)
    		.passwordEncoder(passwordEncoder());
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
                .antMatchers("/static/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http 
        	.csrf()
        		.disable()
        	.authorizeRequests()
            	.antMatchers("/views/**").authenticated()
                .antMatchers("/**").permitAll()
                .and()
	        .formLogin()
		        .loginPage("/intro")
		        .loginProcessingUrl("/loginProcess")
		        .defaultSuccessUrl("/")
		        .failureUrl("/intro?login_error=1")
		        .usernameParameter( "username" )
                .passwordParameter( "password" )
		        .and()
		    .logout()
                .invalidateHttpSession(true)
                .logoutUrl("/logout")
                .deleteCookies("JSESSIONID")
                .logoutSuccessUrl("/")
        		.and()        	
        	.exceptionHandling()
        		.accessDeniedPage("/403")
        		.and()
        	.sessionManagement()
                .maximumSessions( 10 )
                .maxSessionsPreventsLogin(true);
         
        	
    }

    @Bean
    public ShaPasswordEncoder passwordEncoder(){
    	ShaPasswordEncoder encoder = new ShaPasswordEncoder();
        return encoder;
    }

    
}